package com.tgy.jwt.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.tgy.jwt.consts.GlobalConsts;
import com.tgy.jwt.token.CheckResult;
import com.tgy.jwt.token.TokenMgr;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author tanggy
 * @date 2022/4/27 10:16
 */

public class TokenAuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String auth = request.getHeader(HttpHeaders.AUTHORIZATION);
        String token = request.getParameter("token");

        if (StringUtils.isEmpty(auth) && StringUtils.isEmpty(token)) {
            PrintWriter printWriter = response.getWriter();
            response.setContentType("application/json;charset=utf-8");
            JSONObject result = new JSONObject();
            result.put("status", GlobalConsts.REQUEST_FAIL);
            result.put("message",GlobalConsts.JWT_TOKENNULL);
            result.put("data","");
            printWriter.print(result.toJSONString());
            printWriter.flush();
            printWriter.close();
            return false;
        }

        String tokenStr;
        if (StringUtils.isEmpty(auth)){
            tokenStr = token;
        }else {
            tokenStr = auth.length()> 7 ? auth.substring(7) : auth;
        }

        // 验证JWT的签名，返回CheckResult对象
        CheckResult checkResult = TokenMgr.validateJWT(tokenStr);
        if (checkResult.isSuccess()) {
            return true;
        } else {
            JSONObject result = new JSONObject();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
            switch (checkResult.getErrCode()) {
                // 签名过期，返回过期提示码
                case GlobalConsts.JWT_ERRCODE_EXPIRE:
                    PrintWriter printWriter = response.getWriter();
                    result.put("status",GlobalConsts.REQUEST_FAIL);
                    result.put("message",GlobalConsts.JWT_ERRCODE_EXPIRE_MSG);
                    result.put("data","");
                    printWriter.print(result.toJSONString());
                    printWriter.flush();
                    printWriter.close();
                    break;
                // 签名验证不通过
                case GlobalConsts.JWT_ERRCODE_FAIL:
                    PrintWriter printWriter2 = response.getWriter();
                    result.put("status",GlobalConsts.REQUEST_FAIL);
                    result.put("message",GlobalConsts.JWT_ERRCODE_FAIL_MSG);
                    result.put("data","");
                    printWriter2.print(result.toJSONString());
                    printWriter2.flush();
                    printWriter2.close();
                    break;
                default:
                    PrintWriter printWriter3 = response.getWriter();
                    result.put("status",GlobalConsts.REQUEST_FAIL);
                    result.put("message",GlobalConsts.JWT_ERRCODE_FAIL_MSG);
                    result.put("data","");
                    printWriter3.print(result.toJSONString());
                    printWriter3.flush();
                    printWriter3.close();
                    break;
            }
        }
        return false;
    }

}
